<?php
	function f431($sql){
		//data handle instance
		//set request
		//define format
		//set format
		//define query string
		//process time
		//process fitler
		$dataHandle = new DataHandle();
		$dataHandle->setRequest("431");


		$action = getValue($_GET['action']);

		if ($action == "getItems"){
			$error = $dataHandle->processTime($startTime, $endTime);
			if($error == ""){
				//--------------------------------------------
				//fix for sql >= problem
				//we are using getDay function to increment
				//end time for one day
				$timeHandle = new TimeHandle();
				$temp2 = $endTime;
				$timeHandle->getDay($temp2, $temp1, $endTime);
				unset($timeHandle);
				//--------------------------------------------

				$filter = $dataHandle->processFilters($startTime, $endTime, "alm_PLCs","start_time");
				$query = getJSONQuery($filter);

				if($query!==Null)
					print($dataHandle->printJSON($sql, $query));
				else{
					$temp = array();
					$temp['error'] = "431: Bad request";
					print(json_encode($temp));				
				}
			}
			else
				print($error);
		}
		else{
			$temp = array();
			$temp['error'] = "431: Bad request";
			print(json_encode($temp));
		}

		unset($dataHandle);

	}

	function getJSONQuery(&$filter){

		$group = getValue($_GET['group']);
		$tag = getValue($_GET['tag']);


		if($group!==Null and $tag!==Null){

			$queryString = "
				SELECT     
					LTRIM(STR(ROUND(CONVERT(float,duration),0))) + ' ' + RIGHT(CONVERT(VARCHAR, CONVERT(datetime, CONVERT(float,duration) , 114),14),12) as duration,
					LTRIM(RTRIM(CONVERT(varchar(20),start_time , 101))) + ' ' + LTRIM(RTRIM(CONVERT(varchar(20),start_time , 114))) as start_time,
					LTRIM(RTRIM(CONVERT(varchar(20),end_time , 114))) as end_time
				FROM	
					alm_PLCs";

			$queryString = $queryString.$filter;

			$queryString = $queryString." and group_name = '".$group."' AND ";
			$queryString = $queryString." tag_name = '".$tag."' ";

			$oderByFiled = getValue($_GET['sortItem']);
			$oderByValue = getValue($_GET['ascDesc']);

			if($oderByFiled !== "" and $oderByValue !== "")
				$queryString = $queryString." order by ".$oderByFiled." ".$oderByValue;

			return $queryString;
		}
		else 
			return null;
	}
?>